package com.siwei.mes.service.laboratory.factory.concrete.service;

import com.alibaba.fastjson.JSONObject;
import com.siwei.mes.common.util.DateHelper;
import com.siwei.mes.common.util.JsonUtils;
import com.siwei.mes.common.util.NullUtils;
import com.siwei.mes.entity.experiment.CheckBatchConfig;
import com.siwei.mes.entity.experiment.Experiment;
import com.siwei.mes.entity.experiment.ExperimentDetail;
import com.siwei.mes.entity.experiment.concrete.batch.ConcreteKsdj;
import com.siwei.mes.entity.laboratory.DataDefaultUc;
import com.siwei.mes.entity.laboratory.concrete.DataConcreteKs;
import com.siwei.mes.entity.laboratory.concrete.DataConcreteKsk;
import com.siwei.mes.entity.system.TestProjectSpecConfig;
import com.siwei.mes.enums.TestProjectEnum;
import com.siwei.mes.mapper.experiment.ExperimentDetailMapper;
import com.siwei.mes.mapper.laboratory.ConcreteLaboratoryMapper;
import com.siwei.mes.service.laboratory.factory.LaboratoryAbstractService;
import com.siwei.mes.service.laboratory.factory.concrete.ConcreteLaboratoryFactory;
import com.siwei.mes.service.laboratory.factory.entity.LaboratoryDownloadVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 混凝土抗渗等级
 *
 * @Description: 混凝土抗渗等级
 * @Version: 1.0
 * @author: mlchen
 * @date: 2025/3/28 22:08
 */
@Service
public class ConcreteKsdjFactory extends LaboratoryAbstractService implements ConcreteLaboratoryFactory {
    private static final Logger log = LoggerFactory.getLogger("laboratory");
    @Resource
    private ConcreteLaboratoryMapper concreteLaboratoryMapper;
    @Resource
    private ExperimentDetailMapper experimentDetailMapper;

    private final TestProjectEnum testProjectEnum = TestProjectEnum.CONCRETE_PARAM_KSDJ;

    @Override
    public void processUpload(JSONObject objJson, String sampleNo, Experiment experiment, List<CheckBatchConfig> batchConfigList, List<TestProjectSpecConfig> testProjectSpecConfigList, ExperimentDetail detail) {
        log.info("开始上传到协会数据库：【混凝土-{}】", testProjectEnum.getName());
        ConcreteKsdj concreteKsdj = objJson.toJavaObject(ConcreteKsdj.class);

        if (concreteKsdj == null) {
            log.info("【混凝土-{}】数据为空，跳过上传！objJson：{}", testProjectEnum.getName(), objJson);
            return;
        }
        DataConcreteKs dataConcreteKs = new DataConcreteKs();

        if (concreteKsdj.getSsksdj() != null && !concreteKsdj.getSsksdj().isEmpty()) {
            dataConcreteKs.setConclusion("合格" + NullUtils.ifNull(concreteKsdj.getSsksdj()));
        }

        List<DataConcreteKsk> kskList = new ArrayList<>();

        if (concreteKsdj.getKsInfo() != null && !concreteKsdj.getKsInfo().isEmpty()) {
            List<ConcreteKsdj.KsInfo> ksInfo = concreteKsdj.getKsInfo();
            for (ConcreteKsdj.KsInfo ks : ksInfo) {
                DataConcreteKsk dataConcreteKsk = new DataConcreteKsk();
                dataConcreteKsk.setSampleNo(sampleNo);
                dataConcreteKsk.setS1(NullUtils.ifNull(ks.getSyyl()));
                if (StringUtils.isNotBlank(ks.getJysj())) {
                    Date date = DateHelper.parseDateTime(DateHelper.getDefaultDateTimeFormat(), DateHelper.getDefaultLocal(), ks.getJysj());

                    if (date == null) {
                        log.error("加压时间转换错误。。。" + ks.getJysj());
                        throw new RuntimeException("加压时间转换错误。。。" + ks.getJysj());
                    }
                    dataConcreteKsk.setS2(date);
                }
                dataConcreteKsk.setS3(NullUtils.isSs(ks.getSfss1()));
                dataConcreteKsk.setS5(NullUtils.isSs(ks.getSfss2()));
                dataConcreteKsk.setS7(NullUtils.isSs(ks.getSfss3()));
                dataConcreteKsk.setS9(NullUtils.isSs(ks.getSfss4()));
                dataConcreteKsk.setS11(NullUtils.isSs(ks.getSfss5()));
                dataConcreteKsk.setS13(NullUtils.isSs(ks.getSfss6()));
                dataConcreteKsk.setS15(NullUtils.ifNull(ks.getZbr()));
                kskList.add(dataConcreteKsk);
            }
        }


        //设置公共属性
        super.setCommonProperties(sampleNo, experiment, dataConcreteKs, "力学室", concreteKsdj.getJcrq(), detail);

        dataConcreteKs.setSampleName("混凝土抗渗试件");

        //抗渗1
        Map<String, Object> data_jgcl_hntks_ks_mBySampleNo = concreteLaboratoryMapper.findDATA_JGCL_HNTKS_KS_MBySampleNo(sampleNo);

        if (data_jgcl_hntks_ks_mBySampleNo == null) {
            concreteLaboratoryMapper.addDATA_JGCL_HNTKS_KS_M(dataConcreteKs);
        } else {
            concreteLaboratoryMapper.updateDATA_JGCL_HNTKS_KS_M(dataConcreteKs);
        }
        //抗渗2

        List<DataConcreteKsk> data_jgcl_hntks_ks_kBySampleNo = concreteLaboratoryMapper.findDATA_JGCL_HNTKS_KS_KBySampleNo(sampleNo);

        if (data_jgcl_hntks_ks_kBySampleNo.isEmpty()) {
            for (DataConcreteKsk ksk : kskList) {
                concreteLaboratoryMapper.addDATA_JGCL_HNTKS_KS_K(ksk);
            }
        } else {
            //先删除 在新增所有
            concreteLaboratoryMapper.delDATA_JGCL_HNTKS_KS_K(sampleNo);

            for (DataConcreteKsk ksk : kskList) {
                concreteLaboratoryMapper.addDATA_JGCL_HNTKS_KS_K(ksk);
            }
        }


        //项目id 默认为0
        String parameterID = "0";
        //赋值dateDefalutUC
        //存储协会需要做的项目集合
        DataDefaultUc defaultUc = new DataDefaultUc();

        if (concreteKsdj.getSsksdj() != null && !concreteKsdj.getSsksdj().isEmpty()) {
            defaultUc.setConclusion("合格(" + NullUtils.ifNull(concreteKsdj.getSsksdj()) + ")");
            defaultUc.setUcResultValue("合格(" + NullUtils.ifNull(concreteKsdj.getSsksdj()) + ")");
        }


        //defaultUc.setUcTestValue();

        //获取标准值
        for (CheckBatchConfig projectInfo : batchConfigList) {
            if (projectInfo.getTestProjectCode() != null && projectInfo.getTestProjectCode().equals(TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode())) {
                defaultUc.setUcUnit(NullUtils.ifNull(projectInfo.getCheckValueUnit()));
            }
        }

        //根据物料信息设置判断配置
        for (TestProjectSpecConfig test : testProjectSpecConfigList) {
            if (TestProjectEnum.CONCRETE_PARAM_KSDJ.getCode().equals(test.getTestProjectCode())) {
                if (experiment.getMaterialsName() != null && experiment.getMaterialsSpecs() != null && experiment.getMaterialsName().equals(test.getMaterialsName()) && experiment.getMaterialsSpecs().equals(test.getMaterialsSpec())) {
                    String json = test.getObjJson();
                    super.setUcStandardValue(defaultUc, json, "ksdj");
                }
            }
        }

        //赋值
        super.setDefUc(defaultUc, experiment, "力学室", sampleNo, concreteKsdj.getJcrq(), detail);

        defaultUc.setUcParameterID(parameterID);//项目id

        defaultUc.setSampleName("混凝土抗渗试件");

        //新增或修改DataDefaultUc
        super.insertOrUpdateDataDefaultUc(sampleNo, parameterID, defaultUc);
    }

    @Override
    public LaboratoryDownloadVo processDownload(String sampleNo, Experiment experiment, ExperimentDetail detail, Map<String, String> parameterMap) {
        log.info("开始下载协会数据到品控：【混凝土-{}】", testProjectEnum.getName());
        JSONObject objJson = detail.getObjJson();
        ConcreteKsdj concreteKsdj = objJson.toJavaObject(ConcreteKsdj.class);
        if (concreteKsdj == null) {
            log.info("【混凝土-{}】数据为空，跳过下载！objJson：{}", testProjectEnum.getName(), objJson);
            return null;
        }

        //抗渗1
        Map<String, Object> data1 = concreteLaboratoryMapper.findDATA_JGCL_HNTKS_KS_MBySampleNo(sampleNo);
        //抗渗2
        List<DataConcreteKsk> data2 = concreteLaboratoryMapper.findDATA_JGCL_HNTKS_KS_KBySampleNo(sampleNo);

        if (data1 == null && data2.isEmpty()) {
            log.info("查询协会【混凝土-{}】信息为空。跳过下载！sampleNo：【{}】", testProjectEnum.getName(), sampleNo);
            return null;
        }

        if (data1.get("DetectonDate") != null) {
            Date detectonDate = (Date) data1.get("DetectonDate");
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String strDate = sdf.format(detectonDate);
            concreteKsdj.setJcrq(strDate);
        }

        List<ConcreteKsdj.KsInfo> ksInfo = new ArrayList<>();
        int count = 1;
        for (DataConcreteKsk dataConcreteKs : data2) {
            ConcreteKsdj.KsInfo ks = new ConcreteKsdj.KsInfo();
            ks.setIndex(String.valueOf(count));
            if (dataConcreteKs.getS1() != null) {
                ks.setSyyl(dataConcreteKs.getS1());
            }
            if (dataConcreteKs.getS2() != null) {
                Date detectonDate = dataConcreteKs.getS2();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String strDate = sdf.format(detectonDate);
                ks.setJysj(strDate);
            }
            if (dataConcreteKs.getS3() != null) {
                if ("未渗水".equals(dataConcreteKs.getS3())) {
                    ks.setSfss1("否");
                } else {
                    ks.setSfss1("是");
                }
            }
            if (dataConcreteKs.getS5() != null) {
                if ("未渗水".equals(dataConcreteKs.getS5())) {
                    ks.setSfss2("否");
                } else {
                    ks.setSfss2("是");
                }
            }
            if (dataConcreteKs.getS7() != null) {
                if ("未渗水".equals(dataConcreteKs.getS7())) {
                    ks.setSfss3("否");
                } else {
                    ks.setSfss3("是");
                }
            }
            if (dataConcreteKs.getS9() != null) {
                if ("未渗水".equals(dataConcreteKs.getS9())) {
                    ks.setSfss4("否");
                } else {
                    ks.setSfss4("是");
                }
            }
            if (dataConcreteKs.getS11() != null) {
                if ("未渗水".equals(dataConcreteKs.getS11())) {
                    ks.setSfss5("否");
                } else {
                    ks.setSfss5("是");
                }
            }
            if (dataConcreteKs.getS13() != null) {
                if ("未渗水".equals(dataConcreteKs.getS13())) {
                    ks.setSfss6("否");
                } else {
                    ks.setSfss6("是");
                }
            }
            if (dataConcreteKs.getS15() != null) {
                ks.setZbr(dataConcreteKs.getS15());
            }

            ksInfo.add(ks);
            count++;
        }


        concreteKsdj.setKsInfo(ksInfo);


        //对象转json
        JSONObject jsonObject = JsonUtils.beanToObject(concreteKsdj);

        //重新赋值
        detail.setObjJson(jsonObject);

        detail.setEquipment(NullUtils.ifNull(data1.get("Equipment")));
        detail.setTemperature(NullUtils.ifNull(data1.get("Temperature")));
        detail.setHumidness(NullUtils.ifNull(data1.get("Humidity")));
        detail.setExperimentGist(NullUtils.ifNull(data1.get("DetectonRuleCode")));
        detail.setJudgeGist(NullUtils.ifNull(data1.get("AccessRuleCode")));

        if (parameterMap != null && parameterMap.get(detail.getTestProjectCode()) != null) {
            detail.setStatus(parameterMap.get(detail.getTestProjectCode()));
        }
        //修改品控试验数据
        experimentDetailMapper.updateByPrimaryKeySelective(detail);

        return new LaboratoryDownloadVo().setEquipment(detail.getEquipment())
                .setJudgeGist(detail.getJudgeGist())
                .setExperimentGist(detail.getExperimentGist())
                .setTemperature(detail.getTemperature())
                .setHumidness(detail.getHumidness());
    }
}
